package gui;

import classes.Ausencia;
import classes.AusenciaTipo;
import classes.Gozo;
import classes.Servidor;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.GeralException;
import fachada.Fachada;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author roberta.m.carvalho
 */
public class GozoCadastrar extends javax.swing.JFrame {

    Fachada fachada = new Fachada();
    ArrayList<Ausencia> listaAus = new ArrayList<Ausencia>();

    /** Creates new form GozoCadastrar */
    public GozoCadastrar() {
        initComponents();
        this.setIconImage(Login.icone.getImage());
        carregarCombo();
        textDias.setEnabled(false);
        lbStatus.setVisible(false);
        lbStatus2.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbAusencias = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        textDias = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dateInicial = new com.toedter.calendar.JDateChooser();
        jLabel4 = new javax.swing.JLabel();
        lbSaldo = new javax.swing.JLabel();
        btSalvar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        dateFinal = new com.toedter.calendar.JDateChooser();
        lbStatus = new javax.swing.JLabel();
        lbStatus2 = new javax.swing.JLabel();
        btCalcularDias = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Gozo");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Período Aquisitivo:");

        cbAusencias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbAusenciasActionPerformed(evt);
            }
        });

        jLabel2.setText("Qtde Dias:");

        jLabel3.setText("Data Inicial:");

        dateInicial.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dateInicialFocusLost(evt);
            }
        });
        dateInicial.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateInicialPropertyChange(evt);
            }
        });

        jLabel4.setText("Saldo:");

        lbSaldo.setText("Saldo");

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        jLabel5.setText("Data Final:");

        dateFinal.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dateFinalFocusLost(evt);
            }
        });
        dateFinal.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateFinalPropertyChange(evt);
            }
        });

        lbStatus.setText("Status:");

        btCalcularDias.setText("Calcular");
        btCalcularDias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCalcularDiasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbStatus)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cbAusencias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, Short.MAX_VALUE)
                        .addComponent(btSalvar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(textDias, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btCalcularDias))
                    .addComponent(dateInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbSaldo)
                    .addComponent(dateFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbStatus2))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(cbAusencias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(textDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btCalcularDias))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(dateInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5)
                            .addComponent(dateFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btSalvar))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lbSaldo))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbStatus)
                    .addComponent(lbStatus2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbAusenciasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbAusenciasActionPerformed
        int v = cbAusencias.getSelectedIndex();

        for (int b = 0; b < listaAus.size(); b++) {
            if (v == b) {
                lbSaldo.setText(String.valueOf(listaAus.get(b).getSaldo()));
                break;
            }
        }
    }//GEN-LAST:event_cbAusenciasActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        try {
            Fachada f = new Fachada();
            Gozo gozo = new Gozo();
            Servidor servidor = new Servidor();
            servidor.setMatricula(ServidorExibir.matricula);
            Ausencia ausencia = new Ausencia();
            long saldo = 0;
            Date dataAquisFinal = null;
            int v = cbAusencias.getSelectedIndex();

            for (int b = 0; b < listaAus.size(); b++) {
                if (v == b) {
                    ausencia.setCod(listaAus.get(b).getCod());
                    saldo = listaAus.get(b).getSaldo();
                    dataAquisFinal = listaAus.get(b).getAquisitivoFinal();
                    break;
                }
            }


            gozo.setDataInicial(dateInicial.getDate());
            gozo.setDataFinal(dateFinal.getDate());
            gozo.setAusencia(ausencia);
            long dias = calcularDias(dateInicial.getDate(), dateFinal.getDate());
            if (dias > saldo) {
                throw new GeralException("O tempo de gozo tem que ser menor ou igual ao saldo.");
            }
            gozo.setDias(dias);
            ausencia.setSaldo(saldo - dias);
            ausencia.setAquisitivoFinal(dataAquisFinal);
            gozo.setServidor(servidor);
            gozo.setAberto(1);
            gozo.setStatus(1);

            f.inserirGozo(gozo, ausencia);
            JOptionPane.showMessageDialog(null, "Inserido com sucesso!");
            TarefaListarTela tlt = new TarefaListarTela();
            tlt.carregarTbAusencia();
            this.dispose();
        } catch (ConexaoException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
        } catch (ConsultaException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível inserir!\n" + e);
        } catch (GeralException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            this.repaint();
        }

    }//GEN-LAST:event_btSalvarActionPerformed

    private void dateFinalPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateFinalPropertyChange
        if (evt.getPropertyName().equals("date")) {
            Date dataInicio = dateInicial.getDate();

            Date dataFinal = dateFinal.getDate();

            long diferenca = calcularDias(dataInicio, dataFinal);

            if (Integer.parseInt(lbSaldo.getText()) < diferenca) {
                JOptionPane.showMessageDialog(rootPane, "Quantidade de dias maior que o saldo!");
                btSalvar.setEnabled(false);
            } else {
                textDias.setText(String.valueOf(diferenca));
                btSalvar.setEnabled(true);
            }
        }
    }//GEN-LAST:event_dateFinalPropertyChange

    private void dateInicialPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateInicialPropertyChange
        if (evt.getPropertyName().equals("date")) {
            dateFinal.setMinSelectableDate(dateInicial.getDate());
            long saldo = Long.parseLong(lbSaldo.getText());
        }
    }//GEN-LAST:event_dateInicialPropertyChange

    private void dateFinalFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateFinalFocusLost
        // TODO add your handling code here:
        Date dataInicio = dateInicial.getDate();

        Date dataFinal = dateFinal.getDate();

        long diferenca = calcularDias(dataInicio, dataFinal);

        if (Integer.parseInt(lbSaldo.getText()) < diferenca) {
            JOptionPane.showMessageDialog(rootPane, "Quantidade de dias maior que o saldo!");
            btSalvar.setEnabled(false);
        } else {
            textDias.setText(String.valueOf(diferenca));
            btSalvar.setEnabled(true);
        }
    }//GEN-LAST:event_dateFinalFocusLost

    private void btCalcularDiasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCalcularDiasActionPerformed
        // TODO add your handling code here:
        Date dataInicio = dateInicial.getDate();

        Date dataFinal = dateFinal.getDate();

        long diferenca = calcularDias(dataInicio, dataFinal);

        if (Integer.parseInt(lbSaldo.getText()) < diferenca) {
            JOptionPane.showMessageDialog(rootPane, "Quantidade de dias maior que o saldo!");
            btSalvar.setEnabled(false);
        } else {
            textDias.setText(String.valueOf(diferenca));
            btSalvar.setEnabled(true);
        }
    }//GEN-LAST:event_btCalcularDiasActionPerformed

    private void dateInicialFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dateInicialFocusLost
        // TODO add your handling code here:
        dateFinalPropertyChange(null);
    }//GEN-LAST:event_dateInicialFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GozoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GozoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GozoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GozoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GozoCadastrar().setVisible(true);
            }
        });
    }

    public final void carregarCombo() {

        Servidor servidor = new Servidor();
        servidor.setMatricula(ServidorExibir.matricula);
        try {
            listaAus = fachada.listarPeriodos(servidor);
            ArrayList<AusenciaTipo> listaT = (ArrayList<AusenciaTipo>) fachada.listarTipo();
            if (listaAus.isEmpty()) {
                String vazio = "<Não possui>";
                cbAusencias.addItem(vazio);
                btSalvar.setEnabled(false);
            } else {
                for (int i = 0; i < listaAus.size(); i++) {
                    String combo = "", tipo = "";
                    DateFormat formatdata = new SimpleDateFormat("MM-yyyy");
                    Date dataIni = listaAus.get(i).getAquisitivoInicial();
                    String dataI = (formatdata.format(dataIni));
                    Date dataFim = listaAus.get(i).getAquisitivoFinal();
                    String dataF = (formatdata.format(dataFim));
                    for (AusenciaTipo t : listaT) {
                        if (t.getCodTipo() == listaAus.get(i).getTipo().getCodTipo()) {
                            tipo = t.getNome();
                        }
                    }
                    combo = tipo + ": " + dataI + " - " + dataF;
                    cbAusencias.addItem(combo);
                }
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tela.\n" + ex);
        }
    }

    public static long calcularDias(Date dataInicio, Date dataFinal) {

        long diferenca = (dataFinal.getTime()
                - dataInicio.getTime());

        int tempoDia = 1000 * 60 * 60 * 24;

        long diasDiferenca = (diferenca / tempoDia) + 1;

        return diasDiferenca;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCalcularDias;
    private javax.swing.JButton btSalvar;
    private javax.swing.JComboBox cbAusencias;
    private com.toedter.calendar.JDateChooser dateFinal;
    private com.toedter.calendar.JDateChooser dateInicial;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbSaldo;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JLabel lbStatus2;
    private javax.swing.JTextField textDias;
    // End of variables declaration//GEN-END:variables
}
